from zhanshop.controller import Controller
from zhanshop.error import Error
from zhanshop.helper.file import File
from zhanshop.httpclient import HttpClient
from zhanshop.validate import Validate


class Base(Controller):
    @staticmethod
    def getUploadFile(request, key = "file"):
        """
        获取上传的文件路径
        :param request:
        :return:
        """
        if(request.files):
            file = request.files.get(key)
            if(file == None): Error.setError('请使用name='+key+'上传文件', 99999)
            extensions = file.filename.split(".")
            if(len(extensions) == 1): Error.setError(file.filename+"没有后缀名", 99999)
            extension = extensions[-1]
            newFilePath = File.getNewFilePath(extension)
            file.save(newFilePath)
            return newFilePath
        else:
            inputData = Validate(request, {
                key: "required | url"
            }).getData()
            url = inputData[key]
            return Base.download(url)

    @staticmethod
    def download(url):
        extensions = url.split(".")
        if (len(extensions) == 1): Error.setError(url + "没有有效后缀名", 99999)
        extension = extensions[-1]
        newFilePath = File.getNewFilePath(extension)
        client = HttpClient()
        client.download(url, "GET", newFilePath)
        return newFilePath